<?php

class MultiUploadHandler {

	private $token;
	private $files = array();
	private $uploadPath = "";
	private $result = "";

	public function __construct($token, $uploadPath) {
		$this->token = $token;
		$this->uploadPath = $uploadPath;
		$this->update();
	}

	public function getToken() {
		return $this->token;
	}

	public function getResult() {
		$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<uploadResult>\n";
		$xml.= $this->result;
		$xml.= "</uploadResult>\n";
		return $xml;
	}


	public function handle(Array $files) {
		$this->result = "";
		foreach($files as $fileFormId => $fileData) {
			if(empty($fileData['error'])) {
				if(!empty($fileData['name'])) {
					if(!in_array($fileData['name'], array_keys($this->files))) {
						// new file
						$this->saveFile($fileFormId, $fileData);
					}
					else if($this->files[$fileData['name']]['size'] != $fileData['size'])  {
					 // updated existing file
						$this->saveFile($fileFormId, $fileData);
					}
					else {
						// file already exists
						$this->addResultMsg($fileData['name'], $fileFormId, 'EXISTS');
					}
				} // !empty file name
			}
			else {
				// TODO: handle errors
			}
		}
		return $this->result;
	}

	private function saveFile($fileFormId, Array $fileData) {
		if(move_uploaded_file($fileData['tmp_name'], $this->uploadPath . '/' . $fileData['name'])) {
			$this->files[$fileData['name']] = $fileData;
			$this->update();
			$this->addResultMsg($fileData['name'], $fileFormId, 'OK', $fileData['size']);
		}
		else {
			$this->addResultMsg($fileData['name'], $fileFormId, 'ERROR');
		}
	}

	private function addResultMsg($fileName, $fileFormId, $msg, $fileSize = 0) {
		$this->result .= "<file name=\"$fileName\" formId=\"$fileFormId\" result=\"$msg\" size=\"$fileSize\"/>\n";
	}

	public function update() {
		$_SESSION['handler'] = $this;
	}

}
?>